package com.duowei.kitchenshow;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentManager;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.duowei.kitchenshow.bean.Auth;
import com.duowei.kitchenshow.bean.Cfpb_item;
import com.duowei.kitchenshow.bean.Jycssz;
import com.duowei.kitchenshow.bean.Kitchens;
import com.duowei.kitchenshow.event.ShowIn;
import com.duowei.kitchenshow.event.ShowOut;
import com.duowei.kitchenshow.fragment.AuthDialogFragment;
import com.duowei.kitchenshow.fragment.Main2Fragment;
import com.duowei.kitchenshow.fragment.MainFragment;
import com.duowei.kitchenshow.fragment.OutFragment;
import com.duowei.kitchenshow.httputils.Post;
import com.duowei.kitchenshow.service.Net;
import com.duowei.kitchenshow.utils.KeyboardUtil;
import com.duowei.kitchenshow.utils.SpUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.litepal.crud.DataSupport;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener, TextWatcher {
    public static boolean showTable=true;
    private FragmentManager mFm;
    private Button mBtnShow;
    private View mFlOut;
    private KeyboardUtil mKeyboardUtil;
    private static final int REQUEST_EXTERNAL_STORAGE = 1;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private EditText mEtInput;
    private MainFragment mMainFragment;
    private Intent mIntent;
    private String mKitchenName="";
    private Main2Fragment mMain2Fragment;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_main);
        checkPermission();
        mKeyboardUtil = KeyboardUtil.instance();

        setKitchenSql();
        initUI();
        initFragment();
        Post.getInstance().checkVersion(this,false);

        deleteHistoryData();

        //软件授权
        Auth auth = DataSupport.findFirst(Auth.class);
        if(auth==null||!"1".equals(auth.getIsforver())){
            AuthDialogFragment fragment = AuthDialogFragment.newInstance(auth);
            fragment.show(getSupportFragmentManager(),null);
            return;
        }
    }

    @Override
    protected void onStart() {
        super.onStart();
        String ip = (String) SpUtils.get(getString(R.string.serverIp), "");
        Net.url="http://"+ip+":2233/server/ServerSvlt?";
        List<Jycssz> jycsszList = DataSupport.findAll(Jycssz.class);
        if(jycsszList.size()<=0){
            Post.getInstance().postJycssz();
        }
    }

    private void setKitchenSql() {
        List<Kitchens> kitchensList = DataSupport.where("select=?", "1").find(Kitchens.class);
        Net.kitchens="";
        if(kitchensList.size()==1){
            Net.kitchens="a.pos='"+kitchensList.get(0).getBcpjsjm()+"'";
            mKitchenName=kitchensList.get(0).getCbmc();
        }else {
            for (int i = 0; i < kitchensList.size(); i++) {
                if (i == 0) {
                    Net.kitchens += "(a.pos='" + kitchensList.get(i).getBcpjsjm() + "'";
                } else if (i == kitchensList.size() - 1) {
                    Net.kitchens += " or a.pos='" + kitchensList.get(i).getBcpjsjm() + "')";
                } else {
                    Net.kitchens += " or a.pos='" + kitchensList.get(i).getBcpjsjm() + "'";
                }
                mKitchenName+=kitchensList.get(i).getCbmc()+",";
            }
        }
    }

    private void initFragment() {
        mFm = getSupportFragmentManager();
        mMainFragment = new MainFragment();
        mMain2Fragment = new Main2Fragment();
        mFm.beginTransaction().replace(R.id.fl_main, mMainFragment).commit();
        mFm.beginTransaction().replace(R.id.fl_out,new OutFragment()).commit();
    }

    private void initUI() {
        mBtnShow = findViewById(R.id.btn_show);
        mBtnShow.setOnClickListener(this);
        findViewById(R.id.btn_setting).setOnClickListener(this);
        findViewById(R.id.btn_exit).setOnClickListener(this);
        findViewById(R.id.btn_all).setOnClickListener(this);
        findViewById(R.id.btn_out).setOnClickListener(this);
        findViewById(R.id.btn_history).setOnClickListener(this);
        mFlOut = findViewById(R.id.fl_out);
        TextView tvKitchen = findViewById(R.id.kitchen);
        tvKitchen.setText("厨部："+mKitchenName);

        mEtInput = findViewById(R.id.et_input);
        mEtInput.addTextChangedListener(this);
        mEtInput.setOnClickListener(this);
    }

    private void checkPermission() {
        int permission = ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
    }

    private void deleteHistoryData() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                DataSupport.deleteAll(Cfpb_item.class, "date('now', '-7 day') >=date(wcsj)");
                Post.getInstance().deleteHistory();
            }
        },5000);
    }

    @Subscribe
    public void showOut(ShowOut event){
        mFlOut.setVisibility(View.VISIBLE);
    }

    @Subscribe
    public void showIn(ShowIn event){
        mFlOut.setVisibility(View.GONE);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.et_input:
                mKeyboardUtil.initKeyboard(this,this,mEtInput);
                mKeyboardUtil.showKeyboard();
                break;
            case R.id.btn_setting:
                mIntent = new Intent(this, SettingActivity.class);
                startActivity(mIntent);
                finish();
                break;
            case R.id.btn_show:
                showTable=!showTable;
                if(showTable){
                    mFm.beginTransaction().replace(R.id.fl_main,mMainFragment).commit();
                    mBtnShow.setText("按餐桌显示");
                }else{
                    mFm.beginTransaction().replace(R.id.fl_main, mMain2Fragment).commit();
                    mBtnShow.setText("按菜品显示");
                }
                break;
            case R.id.btn_all:
                Post.getInstance().postUpdate(1,showTable);
                break;
            case R.id.btn_history:
                mIntent=new Intent(this,PassRecordsActivity.class);
                startActivity(mIntent);
                break;
            case R.id.btn_out:
                mIntent = new Intent(this, SellOutActivity.class);
                startActivity(mIntent);
                break;
            case R.id.btn_exit:
                finish();
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int start, int count, int after) {
    }
    @Override
    public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
        String s = charSequence.toString().toUpperCase();
        if(showTable){
            mMainFragment.searchCfpb(s);
        }else{
            mMain2Fragment.searchCfpb(s);
        }
    }
    @Override
    public void afterTextChanged(Editable s) {
    }

    //当前APP版本号
    public int getVersion() {
        int versionCode=0;
        PackageManager manager = getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(getPackageName(), 0);
            // 版本名
            versionCode = info.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
}
